import random

from common.ConfigUtil import config
from common.DBUtils import DBUtil

import re

from common.LoggerUtil import log
from common.RequestsUtils import RequestsUtil
from middle_ware.db_hander import MyDBHandler


def mk_phone():
    """随机生成手机号"""
    phone = '1' + random.choice(['3', '5', '7', '8', '9'])
    for i in range(9):
        num = str(random.randint(0, 9))
        phone += num
    return phone


def get_token():
    """登录并获取token"""
    req = RequestsUtil()
    res = req.json('post',
                   config.read('http', 'base_url') + config.read('login', 'login_url'),
                   json={"mobile_phone": config.read('login', 'phone'), "pwd": config.read('login', 'pwd')},
                   headers=eval(config.read('http', 'headers')))
    print(res)
    token_data = {"token": res['data']['token_info']['token'],
                  "member_id": res['data']['id']}
    return token_data


class Context:
    """保存临时替换的数据"""

    # 固定全局变量在配置文件中维护
    reportId = config.read('id', 'reportId')
    accId = config.read('id', 'accId')

    #  需要动态获取的参数变量,在装饰器中维护，实时获取可以查库
    # @property
    # def loan_id(self):
    #     # Context().loan_id
    #     db = MyDBHandler()
    #     loan = db.query("SELECT * FROM loan ORDER BY id DESC;", one=True)
    #     return str(loan['id'])
    #
    # @property
    # def above_balance(self):
    #     db = MyDBHandler()
    #     db_user_info = db.query('SELECT * FROM member WHERE id =%s;',
    #                             args=[self.member_id])
    #     return str(db_user_info['leave_amount'] + 1)


def replace_label(target):
    """
    使用data替换target里的标签，不用replace是因为每次只能替换一个
    :param target:
    :return:
    """
    # 替换规则
    pattern = r"#(.*?)#"
    ctx = Context()
    while re.search(pattern, target):
        # 第一个参数匹配到phone和pwd
        key = re.search(pattern, target).group(1)
        # 动态获取key值
        value = getattr(ctx, key, '')
        target = re.sub(pattern, value, target, 1)
        log.info(f"开始替换请求参数【{key}】替换为【{value}】")
    return target


if __name__ == '__main__':
    print(get_token())
